package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.imp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import net.wimpi.modbus.io.ModbusTCPTransport;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.ConnectionHandlerFactory;

public class Server implements Runnable {
	
	private ConnectionHandlerFactory factory;
	private ServerSocket server;

	public Server(int port,ConnectionHandlerFactory factory){
		
		try {
			
			this.factory = factory;
			this.server = new ServerSocket(port);
			new Thread(this).start();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while(true){
				Socket socket = server.accept();
				new Thread(factory.create(new ModbusTCPTransport(socket))).start();
			}		
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
